package com.skivingcloud.apiplatform.mng.controller;


import com.skivingcloud.admin.annotation.UserOperateLog;
import com.skivingcloud.admin.utils.UserUtil;
import com.skivingcloud.apiplatform.contants.CryptContant;
import com.skivingcloud.apiplatform.mng.entity.ApiPlatformMng;
import com.skivingcloud.apiplatform.mng.service.IApiPlatformMngService;
import com.skivingcloud.apiplatform.signature.service.ExtendCryptService;
import com.skivingcloud.apiplatform.signature.util.SmCryptoUtils;
import com.skivingcloud.common.contants.CommonServiceError;
import com.skivingcloud.common.exception.BusinessException;
import com.skivingcloud.common.utils.PageUtils;
import com.skivingcloud.common.utils.R;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author skivingcloud
 * @since 2022-11-01
 */
@RestController
@RequestMapping("/apiplantform/mng")
@Api
public class ApiPlatformMngController {

    private static Logger log = LoggerFactory.getLogger(ApiPlatformMngController.class);

    @Autowired
    private IApiPlatformMngService apiPlatformMngService;
    @Autowired
    private Map<String, ExtendCryptService> extendCryptBeanMap;

    /**
     * 分页查询
     * @param page
     * @param limit
     * @param dataForm
     * @return
     */
    @GetMapping("/list")
    public R list(String page, String limit, String dataForm) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("page", page);
        params.put("limit", limit);
        params.put("dataForm", dataForm);
        PageUtils pages = apiPlatformMngService.queryPage(params);
        return R.ok().put("page", pages);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") String id) throws Exception {
        ApiPlatformMng apiPlatformMng = apiPlatformMngService.selectById(id);
        return R.ok().put("data", apiPlatformMng);
    }

    /**
     * 根据appId查询
     * @param appId
     * @return
     * @throws Exception
     */
    @GetMapping("/selectByAppId/{appId}")
    public R selectByAppId(@PathVariable("appId") String appId) throws Exception {
        ApiPlatformMng apiPlatformMng = apiPlatformMngService.selectByAppId(appId);
        return R.ok().put("data", apiPlatformMng);
    }

    /**
     * 新增接口配置
     * @param apiPlatformMng
     * @return
     */
    @UserOperateLog(module = "系统功能", methods = "save", description = "新增api接口配置")
    @PostMapping("/save")
    public R save(@RequestBody ApiPlatformMng apiPlatformMng) {
        try {
            apiPlatformMngService.save(apiPlatformMng, UserUtil.getUser().getId());
            return R.ok();
        }  catch (BusinessException e){
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error(CommonServiceError.SERVICE_SAVE.getMsg() + "api接口配置" + CommonServiceError.SERVICE_FAILURE.getMsg(), e);
            return R.error(CommonServiceError.SERVICE_SAVE.getMsg() + "api接口配置" + CommonServiceError.SERVICE_FAILURE.getMsg());
        }
    }

    /**
     * 修改接口配置
     * @param apiPlatformMng
     * @return
     */
    @UserOperateLog(module = "系统功能", methods = "update", description = "修改api接口配置")
    @PostMapping("/update")
    public R update(@RequestBody ApiPlatformMng apiPlatformMng) {
        try {
            apiPlatformMngService.update(apiPlatformMng, UserUtil.getUser().getId());
            return R.ok();
        }  catch (BusinessException e){
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error(CommonServiceError.SERVICE_MODIFY.getMsg() + "api接口配置" + CommonServiceError.SERVICE_FAILURE.getMsg(), e);
            return R.error(CommonServiceError.SERVICE_MODIFY.getMsg() + "api接口配置" + CommonServiceError.SERVICE_FAILURE.getMsg());
        }
    }

    /**
     * 删除接口配置
     * @param ids
     * @return
     */
    @UserOperateLog(module = "系统功能", methods = "delete", description = "删除api接口配置")
    @PostMapping("/delete")
    public R delete(@RequestBody String[] ids) {
        try {
            apiPlatformMngService.deleteBatch(ids);
            return R.ok();
        } catch (BusinessException e){
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error(CommonServiceError.SERVICE_DELETE.getMsg() + "api接口配置" + CommonServiceError.SERVICE_FAILURE.getMsg(), e);
            return R.error(CommonServiceError.SERVICE_DELETE.getMsg() + "api接口配置" + CommonServiceError.SERVICE_FAILURE.getMsg());
        }
    }

    @PostMapping("/getSecretByAlgorithm")
    public R getSecretByAlgorithm(@RequestBody ApiPlatformMng apiPlatformMng) throws Exception {
        try {
            switch(apiPlatformMng.getEncryption()){
                case CryptContant.CRYPT_ALGORITHM_SM2:
                    Map<String, String> map = SmCryptoUtils.getSM2Key();
                    apiPlatformMng.setAppSecret(map.get("publicKey"));
                    apiPlatformMng.setAppPrivateSecret(map.get("privateKey"));
                    break;
                case CryptContant.CRYPT_ALGORITHM_SM3:
                case CryptContant.CRYPT_ALGORITHM_MD5:
                case CryptContant.CRYPT_ALGORITHM_SHA256:
                case CryptContant.CRYPT_ALGORITHM_SHA512:
                    apiPlatformMng.setAppSecret(SmCryptoUtils.getMd5Salt());
                    break;
                case CryptContant.CRYPT_ALGORITHM_SM4:
                    apiPlatformMng.setAppSecret(SmCryptoUtils.getSM4Key());
                    break;
                case CryptContant.CRYPT_ALGORITHM_AES128:
                    apiPlatformMng.setAppSecret(SmCryptoUtils.getAesKey(16));
                    break;
                case CryptContant.CRYPT_ALGORITHM_AES256:
                    apiPlatformMng.setAppSecret(SmCryptoUtils.getAesKey(32));
                    break;
                case CryptContant.CRYPT_ALGORITHM_RSA:
                    Map<String, String> mapRsa = SmCryptoUtils.getRsaKey();
                    apiPlatformMng.setAppSecret(mapRsa.get("publicKey"));
                    apiPlatformMng.setAppPrivateSecret(mapRsa.get("privateKey"));
                    break;
                case CryptContant.CRYPT_ALGORITHM_EXTEND:
                    ExtendCryptService extendCryptService = extendCryptBeanMap.get(apiPlatformMng.getEncBean());
                    if(StringUtils.isBlank(apiPlatformMng.getCryptType())){
                        return R.error("必须传入算法类型");
                    }
                    apiPlatformMng = extendCryptService.getSecret(apiPlatformMng);
                    break;
                default:
                    if(apiPlatformMng.getEncryption().startsWith("Hmac")){
                        apiPlatformMng.setAppSecret(SmCryptoUtils.getHmacKey(apiPlatformMng.getEncryption()));
                    }else{
                        return R.error("不支持的算法类型");
                    }
                    break;
            }
            return R.ok().put("data", apiPlatformMng);
        } catch (Exception e) {
            log.error("生成秘钥失败", e);
            return R.error("生成秘钥失败");
        }
    }

}
